package textapp.business;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import textapp.dao.AppConfigDao;
import textapp.dao.model.AppConfig;

// SINGLETON
public class AppConfigService {
	private String pushAuthToken;
	
	private static AppConfigService singleton;
	
	private AppConfigService() {
		
	}
	
	public static AppConfigService getInstance() {
		if (singleton == null) {
			singleton = new AppConfigService();
		}
		return singleton;
	}
	
	private String PUSH_AUTH_PARAM = "PUSH_AUTH_TOKEN";
	

	public synchronized String getPushAuthToken() {
		if (this.pushAuthToken == null) {
			AppConfigDao dao = new AppConfigDao();
			AppConfig ac = dao.findByName(PUSH_AUTH_PARAM);
			if (ac == null) {
				// get the ac here
				ac = new AppConfig();
				ac.setParam(PUSH_AUTH_PARAM);
				String aToken = requestForAuthToken();
				ac.setValue(aToken);
				dao.saveOrUpdate(ac);
			}
			this.pushAuthToken = ac.getValue();
		}
		return this.pushAuthToken;
	}
	
	public boolean saveOrUpdatePushAuthToken(String newValue) {
		try {
			AppConfig ac = new AppConfig();
			ac.setParam(PUSH_AUTH_PARAM);
			ac.setValue(newValue);
			
			AppConfigDao dao = new AppConfigDao();
			dao.saveOrUpdate(ac);
			this.pushAuthToken = newValue;
			return true;
		} catch(Throwable t) {
			return false;
		}
		
	}
	
	private String GMAIL_USER = "theappmakers@gmail.com";
	private String GMAIL_PASS = "textitapp";
	private String PUSH_SERVICE = "ac2dm";
	private String PUSH_SOURCE = "textitsrc";
	private String PUSH_ACC_TYPE = "HOSTED_OR_GOOGLE";
	private String GOOGLE_CLIENTLOGIN_URL = "https://www.google.com/accounts/ClientLogin";
	
	private String requestForAuthToken() {
		System.out.println("NEW Request");
		
		HttpResponse res = null;
	    try {
	        DefaultHttpClient client = new DefaultHttpClient();
	        URI uri = new URI(GOOGLE_CLIENTLOGIN_URL);

	        
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("accountType", PUSH_ACC_TYPE));
	        params.add(new BasicNameValuePair("Email", GMAIL_USER));
	        params.add(new BasicNameValuePair("Passwd", GMAIL_PASS));
	        params.add(new BasicNameValuePair("service", PUSH_SERVICE));
	        params.add(new BasicNameValuePair("source", PUSH_SOURCE));

	        HttpPost post = new HttpPost(uri);
	        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
	        post.setEntity(entity);
	        res = client.execute(post);
	    } catch (Exception e) {
	        e.printStackTrace();
	    } 

	    if (res != null) {
	        try {
	        	
				InputStreamReader reader = new InputStreamReader(res.getEntity().getContent());
				BufferedReader buff = new BufferedReader(reader);
				
				String line = buff.readLine();
				StringBuilder result = new StringBuilder(line);
				while ((line = buff.readLine()) != null) {
					result.append("\n");
					result.append(line);
				}
				
				System.out.println("NOT NULL");
				System.out.println(result.toString());
				
				String[] resultArr = result.toString().split("\n");
				String resultAuth = resultArr[2];
				resultAuth = resultAuth.substring(5);
				return resultAuth;
				
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    } else {
	    	System.out.println("NULL RESPONSE");
	    }
	    return null;
	}
	
	public static void main(String[] args) {
		AppConfigService service = AppConfigService.getInstance();
		String token = service.getPushAuthToken();
		System.out.println("1: "+token);
		
		String token2 = service.getPushAuthToken();
		System.out.println("2: "+token2);
		
		String token3 = service.getPushAuthToken();
		System.out.println("3: "+token3);
		
		
		
		//String str  = service.getPushAuthToken();
		
		//System.out.println("AT: "+str);
		
//		service.saveOrUpdatePushAuthToken("TEst value 1234");
//		System.out.println(service.getPushAuthToken());
	}
}
